package com.zhongke.common.widget

import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.zhongke.common.R
import com.zhongke.common.adapter.SimpleViewHolder
import com.zhongke.common.databinding.CommonBottomSheetBinding
import com.zhongke.common.utils.dp

/**
 * @author: ZhangQingHua
 * @date: 2021/11/27
 * @description 从屏幕底部弹出的菜单
 */
class ZKBottomSheet(
    private val context: Context,
    private val items: List<String>,
    private val itemClickCallback: (position: Int) -> Unit
) {

    val dialog: BottomSheetDialog

    init {
        val binding: CommonBottomSheetBinding = DataBindingUtil.inflate(
            LayoutInflater.from(context), R.layout.common_bottom_sheet, null, false
        )
        dialog = BottomSheetDialog(context).apply {
            setContentView(binding.root)
        }
        binding.root.apply {
            // 去掉 Dialog 自带的背景
            (parent as View).setBackgroundColor(Color.TRANSPARENT)
        }
        binding.list.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            addItemDecoration(ItemDivider(context, ItemDivider.VERTICAL, 1.dp, R.color.base_color_333333, 16.dp, 16.dp))
            adapter = object : RecyclerView.Adapter<SimpleViewHolder>() {
                override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder {
                    val tv = TextView(context)
                    tv.setTextColor(context.getColor(R.color.base_color_333333))
                    tv.textSize = 20f
                    tv.gravity = Gravity.CENTER
                    tv.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 60.dp)
                    return SimpleViewHolder(tv)
                }

                override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) {
                    (holder.itemView as TextView).text = items[position]
                    holder.itemView.setOnClickListener {
                        itemClickCallback(position)
                        dismiss()
                    }
                }

                override fun getItemCount() = items.size
            }
        }
    }

    fun show() {
        dialog.show()
    }

    fun dismiss() {
        dialog.dismiss()
    }

}